/**
 * Created by DevilsEyes on 2016/2/13.
 * ==========================
 *         文档 doc
 * ==========================
 * 用于存放所爬文档的数据结构
 *
 */
'use strict';
var db = require('../unit/db.js').mongoose;
var Schema = db.Schema;

var doc_Schema = new Schema({

    id: String,

    //链接
    link: String,

    //标题
    title: String,

    //深度
    deep: Number,

    //状态(匹配值)
    status: Number,
    // -1: 弃用
    // 0: 未匹配
    // 1+：匹配程度

    //来源
    root: String,
    // B0 - B999
    // G0 - G999

    //获取路径
    path:String,

    //匹配关键字列表
    weight:String,

    updated: {
        type: Number,
        default: new Date().getTime()
    }
});

var doc_Model = db.model("doc", doc_Schema);

var id = 0;

module.exports = {

    save: (obj) => {
        obj.id = Date.now() + '_' + id;
        id++;
        var doc_Entity = new doc_Model(obj);

        return doc_Entity.save()
    },

    update: (id, obj) => {
        var cp = {};
        if (obj.title)cp.title = obj.title;
        if (obj.link)cp.link = obj.link;
        if (obj.status)cp.status = obj.status;
        if (obj.weight)cp.weight = obj.weight;

        return doc_Model
            .find({id: id})
            .update(cp)
    },

    //查重
    isRepeated(link){
        return new Promise((done, fail)=> {
            doc_Model
                .findOne({link: link})
                .then((err, doc) => {
                    if (err)
                        fail(err);
                    else if (doc)
                        fail(new Error('重复的链接'));
                    else
                        done();
                });
        })
    },

    getAll: () => {
        return doc_Model
            .find({})
            .sort({status: 'desc'});
    },

    getSome: (limit) => {
        return doc_Model
            .find({status: 0})
            .sort({deep: 'desc', id: 'asc'})
            .limit(limit)
    },

    clear: (callback) => {
        return doc_Model.remove({}).then(callback);
    },

    $Model: doc_Model

};